package org.jeecg.modules.paycenter.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.paycenter.channel.pufa.PfBankUtil;
import org.jeecg.modules.paycenter.enums.PayChannelEnum;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.wlhy.customer.entity.HyCustomerAccountBook;
import org.jeecg.modules.wlhy.customer.service.IHyCustomerAccountBookService;
import org.jeecg.modules.wlhy.customerwallet.entity.HyCustomerWallet;
import org.jeecg.modules.wlhy.customerwallet.entity.HyCustomerWalletRecharge;
import org.jeecg.modules.wlhy.customerwallet.service.IHyCustomerWalletService;
import org.jeecg.modules.wlhy.hyconfig.entity.HyConfig;
import org.jeecg.modules.wlhy.hypfaccount.entity.HyPfAccount;
import org.jeecg.modules.wlhy.hypfaccount.service.IHyPfAccountService;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteService;
import org.jeecg.modules.wlhy.tlaccount.entity.HyTlAccount;
import org.jeecg.modules.wlhy.tlaccount.service.IHyTlAccountService;
import org.jeecg.modules.wlhy.utils.HyCfgUtil;
import org.jeecg.modules.wlhy.utils.HyConfigUtils;
import org.jeecg.modules.wlhy.utils.UserUtil;
import org.jeecg.modules.wlhy.walletcfg.entity.HyWalletCfg;
import org.jeecg.modules.wlhy.walletcfg.service.IHyWalletCfgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 系统钱包配置服务类,如密码、免密支付等配置
 */
@Service
public class WalletService {

    @Autowired
    private IHyWalletCfgService hyWalletCfgService;

    @Autowired
    ISysUserService sysUserService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private IHyCustomerAccountBookService hyCustomerAccountBookService;

    @Autowired
    private IHyCustomerWalletService hyCustomerWalletService;

    @Autowired
    private IHyPfAccountService hyPfAccountService;

    @Autowired
    private IHyTlAccountService hyTlAccountService;

    @Autowired
    private PfBankUtil pfBankUtil;

    @Autowired
    private IHyShippingNoteService hyShippingNoteService;

    //获取货主钱包（农行和系统钱包）
    public Map getCustomerWallets(String customerId) {
        HyConfig config = HyConfigUtils.getConfig();
        Map<String,Object> data = new HashMap<>();
        //农行钱包
        if(config.getNhbankIzUse()) {
            HyCustomerAccountBook nhWallet = hyCustomerAccountBookService.getWalletInfo(customerId);
            if(nhWallet != null){
                data.put("nhWallet", nhWallet);
                data.put("nhST" , "1");
            }else {
                data.put("nhST", "2");
            }
        }else {
            data.put("nhST" , "0");
        }
        //系统钱包
        HyCustomerWallet sysWallet = hyCustomerWalletService.getWalletInfo(customerId);
        if(sysWallet != null) {
            data.put("sysWallet", sysWallet);
            data.put("sysST" , "1");
        }else {
            data.put("sysST" , "2");
        }
        //中信钱包,待完成
        //浦发钱包
        if(config.getPfIzUse()){
            HyPfAccount customerAccount = hyPfAccountService.getCustomerAccount(customerId);
            if(customerAccount!=null) {
                customerAccount.setAcctNo(config.getPfAccNo());
                customerAccount.setKhh(config.getPfKhh());
                pfBankUtil.getChildAccountBalInfo(customerAccount);
                data.put("pfWallet", customerAccount);
                data.put("pfST" , "1");
            }else {
                data.put("pfST" , "2");
            }
        } else {
            data.put("pfST" , "0");
        }
        //通联
        if(HyCfgUtil.isTongLianUsed()){
            HyTlAccount account = hyTlAccountService.getByUid(customerId);
            if(account != null){
                data.put("tlWallet", account);
                data.put("tlST" , "1");
                BigDecimal djsFee = hyShippingNoteService.getCustomerDjsFee(customerId);
                account.setDjsFee(djsFee);
                BigDecimal totalFee = hyShippingNoteService.getCustomerTotalFeeByChannel(customerId , PayChannelEnum.TONGLIAN.channelType);
                account.setTotalFee(totalFee);
            }else {
                data.put("tlST" , "2");
            }
        }else {
            data.put("tlST" , "0");
        }

        return data;
    }

    public HyWalletCfg getByUidAndUtype(String uid , String utype){
        return hyWalletCfgService.getOne(new QueryWrapper<HyWalletCfg>()
                .eq("utype",utype)
                .eq("uid",uid)
        );
    }

    public HyWalletCfg getLoginUserWalletCfg(){
        LoginUser loginUser = UserUtil.getLoginUser();
        if (loginUser == null) {
            throw new JeecgBootException("未获取到登录信息");
        }
        return hyWalletCfgService.getOne(new QueryWrapper<HyWalletCfg>()
                .eq("utype",loginUser.getUType())
                .eq("uid",loginUser.getId())
        );
    }

    //region 支付密码
    public void addPwd(JSONObject jsonObject) {
        String password = jsonObject.getString("password");
        if (StringUtils.isEmpty(password)) {
            throw new JeecgBootException("支付密码不能为空！");
        }
        LoginUser loginUser = UserUtil.getLoginUser();
        if (loginUser == null) {
            throw new JeecgBootException("未获取到登录信息");
        }
        String uid = loginUser.getId();
        String utype = loginUser.getUType();
        HyWalletCfg cfg = this.getByUidAndUtype(uid , utype);
        if (cfg != null) {
            throw new JeecgBootException("已设置密码,不能重复设置");
        }
        String encryptPayPwd = PasswordUtil.encrypt(uid, password, PasswordUtil.BSalt);
        cfg = new HyWalletCfg();
        cfg.setPwd(encryptPayPwd);
        cfg.setUid(uid);
        cfg.setUtype(utype);
        hyWalletCfgService.save(cfg);
    }

    public void setPwd(JSONObject jsonObject) {
        String oldPwd = jsonObject.getString("oldpassword");
        String password = jsonObject.getString("password");
        if(StringUtils.isEmpty(oldPwd)){
            throw new JeecgBootException("原始支付密码不能为空！");
        }
        if(StringUtils.isEmpty(password)){
            throw new JeecgBootException("新支付密码不能为空！");
        }
        HyWalletCfg cfg = this.getLoginUserWalletCfg();
        if (cfg == null) {
            throw new JeecgBootException("尚未设置支付密码");
        }
        String uid = cfg.getUid();
        String encryptPayPwd = PasswordUtil.encrypt(uid, oldPwd,  PasswordUtil.BSalt);
        if(!StringUtils.equals(encryptPayPwd,cfg.getPwd())){
            throw new JeecgBootException("原始支付密码错误");
        }
        String newEncryptPayPwd = PasswordUtil.encrypt(uid, password,  PasswordUtil.BSalt);
        cfg.setPwd(newEncryptPayPwd);
        hyWalletCfgService.updateById(cfg);
    }

    public void resetPwd(JSONObject jsonObject) {
        String captcha = jsonObject.getString("captcha");
        String password = jsonObject.getString("password");
        if (StringUtils.isEmpty(captcha)) {
            throw new JeecgBootException("验证码不能为空！");
        }
        if (StringUtils.isEmpty(password)) {
            throw new JeecgBootException("新支付密码不能为空！");
        }

        LoginUser loginUser = UserUtil.getLoginUser();
        if (loginUser == null) {
            throw new JeecgBootException("未获取到登录信息");
        }
        String uid = loginUser.getId();
        String utype = loginUser.getUType();
        HyWalletCfg cfg = this.getByUidAndUtype(uid , utype);
        if (cfg == null) {
            throw new JeecgBootException("尚未设置支付密码");
        }

        String phone = loginUser.getPhone();
        Object code = redisUtil.get(phone);
        if (!captcha.equals(code)) {
            throw new JeecgBootException("验证码错误");
        }

        String newEncryptPayPwd = PasswordUtil.encrypt(uid, password,  PasswordUtil.BSalt);
        cfg.setPwd(newEncryptPayPwd);
        hyWalletCfgService.updateById(cfg);
    }

    public boolean checkPwd(String pwd) {
        HyWalletCfg cfg = this.getLoginUserWalletCfg();
        if (cfg == null) {
            throw new JeecgBootException("尚未设置支付密码");
        }
        String encryptPayPwd = PasswordUtil.encrypt(cfg.getUid(), pwd, PasswordUtil.BSalt);
        if (StringUtils.equals(encryptPayPwd, cfg.getPwd())) {
            return true;
        }
        return false;
    }
    //endregion


    //region 系统钱包

    @Transactional
    public HyCustomerWalletRecharge exchange(String customerId, BigDecimal amt, String channel, String remark) {

        if(amt == null){
            throw new JeecgBootException("金额不正确！");
        }
        //<=0
        if(amt.compareTo(BigDecimal.ZERO) < 1){
            throw new JeecgBootException("金额不正确！");
        }
        HyCustomerWallet customerWallet = hyCustomerWalletService.getByCustomerIdForUpdate(customerId);
        if (customerWallet == null) {
            throw new JeecgBootException("钱包信息不存在！");
        }
        if (!customerWallet.izEnoughAmt(amt)) {
            throw new JeecgBootException("余额不足");
        }
        return hyCustomerWalletService.exchange(customerWallet, amt, channel, remark);
    }

    @Transactional
    public void recharge(String customerId, BigDecimal amt, String remark) {
        if(amt == null){
            throw new JeecgBootException("金额不正确！");
        }
        //<=0
        if(amt.compareTo(BigDecimal.ZERO) < 1){
            throw new JeecgBootException("金额不正确！");
        }
        HyCustomerWallet customerWallet = hyCustomerWalletService.getByCustomerIdForUpdate(customerId);
        if (customerWallet == null) {
            throw new JeecgBootException("钱包信息不存在！");
        }
        hyCustomerWalletService.recharge(customerWallet, amt, remark);
    }

    @Transactional
    public void kc(String customerId, BigDecimal amt, String remark) {
        if(amt == null){
            throw new JeecgBootException("金额不正确！");
        }
        //<=0
        if(amt.compareTo(BigDecimal.ZERO) < 1){
            throw new JeecgBootException("金额不正确！");
        }
        HyCustomerWallet customerWallet = hyCustomerWalletService.getByCustomerIdForUpdate(customerId);
        if (customerWallet == null) {
            throw new JeecgBootException("钱包信息不存在！");
        }
        if (!customerWallet.izEnoughAmt(amt)) {
            throw new JeecgBootException("余额不足");
        }
        hyCustomerWalletService.kc(customerWallet, amt, remark);
    }



    //endregion

}
